
package com.baomidou.mybatisplus.autoconfigure;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.ddl.DdlHelper;
import com.baomidou.mybatisplus.extension.ddl.IDdl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.List;

/**
 * DDL 启动应用后执行
 *
 * @author hubin
 * @since 2021-06-22
 */
@Slf4j
public class DdlApplicationRunner implements ApplicationRunner {

    private final List<IDdl> ddlList;

    public DdlApplicationRunner(List<IDdl> ddlList) {
        this.ddlList = ddlList;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.debug("  ...  DDL start create  ...  ");
        if (ObjectUtils.isNotEmpty(ddlList)) {
            /**
             * 执行 SQL 脚本
             * <p>多数据源情况可按需初始化</p>
             */
            ddlList.forEach(ddl -> ddl.runScript(dataSource -> DdlHelper.runScript(ddl.getDdlGenerator(),
                    dataSource, ddl.getSqlFiles(), true)));
        }
        log.debug("  ...  DDL end create  ...  ");
    }

}
